import request from '../../utils/request'

Page({
  data: {
    startDate: '',
    endDate: '',
    tabs: [],
    currentTab: 0,
    newCount: 0,
    updateCount: 0,
    displayData: []
  },

  onLoad() {
    const today = new Date();
    const tabs = [];

    for (let i = 4; i >= 0; i--) {
      const d = new Date(today);
      d.setDate(today.getDate() - i);
      tabs.push(this.formatDate(d, 'MM-dd'));
    }

    const currentTab = 4; // 默认今天
    const selectedDate = new Date(today);
    const nextDate = new Date(today);
    // nextDate.setDate(today.getDate() + 1);

    this.setData({
      tabs,
      currentTab,
      startDate: this.formatDate(selectedDate, 'yyyy-MM-dd'),
      endDate: this.formatDate(nextDate, 'yyyy-MM-dd')
    });

    this.fetchUploadData();
  },

  formatDate(date, format) {
    const pad = n => (n < 10 ? '0' + n : n);
    const yyyy = date.getFullYear();
    const MM = pad(date.getMonth() + 1);
    const dd = pad(date.getDate());

    if (format === 'yyyy-MM-dd') return `${yyyy}-${MM}-${dd}`;
    if (format === 'MM-dd') return `${MM}-${dd}`;
    return '';
  },

  onTabChange(e) {
    const index = e.currentTarget.dataset.index;
    const baseDate = new Date();
    baseDate.setDate(baseDate.getDate() - (4 - index)); // 选中某天
    const baseDateObj = this.formatDate(baseDate, 'yyyy-MM-dd')
    const startDate = baseDateObj;
    const endDate = baseDateObj;

    this.setData({
      currentTab: index,
      startDate,
      endDate
    });

    this.fetchUploadData();
  },

  onStartDateChange(e) {
    this.setData({ 
      startDate: e.detail.value,
      currentTab: -1
    });
    this.fetchUploadData();
  },

  onEndDateChange(e) {
    this.setData({ endDate: e.detail.value });
    this.fetchUploadData();
  },

  sendToEmail() {
    wx.showToast({
      title: '记录已发送',
      icon: 'success'
    });
  },

  goBack() {
    wx.navigateBack();
  },
  fetchUploadData() {
    const { startDate, endDate } = this.data;
  
    wx.showLoading({ title: '加载中' });
  
    request({
      url: 'material/statistics', // 你封装的 request 应该自动带了 baseURL（如 http://localhost:8007/api/）
      method: 'GET',
      data: {
        date: startDate, // 示例：'2025-07-16'
        startDate,
        endDate
      }
    })
      .then(res => {
        wx.hideLoading();
  
        const data = res.data || {};
        this.setData({
          newCount: data.newCount || 0,
          updateCount: data.updateCount || 0,
          loading: false,
          displayData: data.dailyStats
        });
      })
      .catch(err => {
        wx.hideLoading();
        this.setData({ loading: false });
        setTimeout(() => {
          wx.showToast({
            title: err.message || '请求失败',
            icon: 'none',
            duration: 3000
          });
        }, 100);
      });
  }
  
});
